import request from '@/utils/request'
import { excelApi } from '@/api/excel'

/**
 * Excel导入相关API
 */

/**
 * 下载Excel模板
 */
export const downloadTemplate = async (entityName) => {
  console.log("正在下载模板:", entityName)
  try {
    const response = await excelApi.downloadTemplate(entityName)
    console.log("完整响应:", response)
    console.log("响应数据:", response.data)
    console.log("响应数据类型:", typeof response.data)
    console.log("是否为Blob:", response.data instanceof Blob)
    console.log("响应状态:", response.status)
    console.log("响应头:", response.headers)
    
    // 情况1: 如果response直接是Blob对象
    if (response instanceof Blob) {
      console.log("✅ 响应直接是Blob对象，直接返回")
      return response
    }
    
    // 情况2: 如果是标准axios响应格式
    if (response && typeof response === 'object') {
      // 检查响应状态
      if (response.status === 200 || !response.status) {
        // 如果data是Blob，直接返回
        if (response.data instanceof Blob) {
          console.log("✅ 响应数据是Blob，返回data")
          return response.data
        }
        // 如果data是其他格式，尝试转换为Blob
        else if (response.data) {
          console.log("⚠️ 尝试转换数据为Blob")
          const blob = new Blob([response.data], { 
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
          })
          return blob
        }
      }
      
      throw new Error(`响应状态异常: ${response.status}`)
    }
    
    throw new Error(`无法识别的响应格式: ${typeof response}`)
  } catch (error) {
    console.error('下载模板失败:', error)
    console.error('错误详情:', error.response || error.message)
    throw error // 重新抛出错误，让调用方处理
  }
}

/**
 * 导入Excel文件
 */
export const importExcel = async (file, entityName, options = {}) => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('targetModelName', entityName)
    
    Object.keys(options).forEach(key => {
      formData.append(key, options[key])
    })
    
    const response = await request.post('/excel/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    return response
  } catch (error) {
    console.error('导入Excel失败:', error)
    throw error
  }
}

/**
 * 验证Excel文件
 */
export const validateExcel = async (file, entityName) => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('targetModelName', entityName)
    
    const response = await request.post('/excel/validate', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    return response
  } catch (error) {
    console.error('验证Excel失败:', error)
    return {
      success: false,
      message: '验证失败: ' + error.message
    }
  }
}

